import json
import datetime
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.views import APIView
from rest_framework.response import Response
from bookshop import models
from bookshop.sers import BookModelSerializer, TypesSerializer, UserModelSerializer
from rest_framework.viewsets import ModelViewSet


@csrf_exempt
def login(request):
    """登陆程序"""
    data = json.loads(request.body)
    user = models.UserInfo.objects.filter(phone=data['phone']).first()
    if user:
        ser = UserModelSerializer(instance=user)
        if user.code == data['code']:
            return JsonResponse({'msg': 1, 'data': ser.data, 'status': 200})  # 1:登陆成功
        else:
            # 3:密码错误
            return JsonResponse({'msg': 3, 'status': 200})
    else:
        # 2:用户不存在
        return JsonResponse({'msg': 2, 'status': 200})


def check(req):
    """检查并修改用户状态"""
    users = models.UserInfo.objects.all()
    for user in users:
        ser = UserModelSerializer(instance=user)
        id = user.idcard
        # n = len(ser.userinfo_userbooks)
        if ser.data['userinfo_userbooks']:             # 书架不为空
            if ser.data['blacklist'] == '正常':
                for book in ser.data['userinfo_userbooks']:
                    date1 = book['time']
                    date1 = datetime.datetime.strptime(date1, '%Y-%m-%d')
                    date2 = datetime.datetime.now()
                    days = (date2 - date1).days
                    if days >= 90 & days < 93:   # 超时未满三天，仅提醒
                        models.UserInfo.objects.filter(idcard=id).update(blacklist=4)
                    if days >= 93 & days < 97:   # 超时三天, 封号
                        models.UserInfo.objects.filter(idcard=id).update(blacklist=3, time=date2)
                    if days >= 97:               # 拉黑
                        models.UserInfo.objects.filter(idcard=id).update(blacklist=2, time=date2)
            elif ser.data['blacklist'] == '封号':
                date1 = ser.data['time']
                date1 = datetime.datetime.strptime(date1, '%Y-%m-%d')
                date2 = datetime.datetime.now()
                days = (date2 - date1).days
                if days >= 30:
                    models.UserInfo.objects.filter(idcard=id).update(blacklist=1)

    return HttpResponse()